﻿/*
** Xin YUAN, 2021, BSD (2)
*/

////////////////////////////////////////////////////////////////////////////////

#include "base/_sys_process.h"

////////////////////////////////////////////////////////////////////////////////

//sub_process

class sub_process
{
public:
	sub_process() noexcept : m_iExitCode(-1)
	{
	}
	sub_process(const sub_process&) = delete;
	sub_process(sub_process&& src) noexcept : m_process(rv_forward(src.m_process)),
						m_iExitCode(src.m_iExitCode)
	{
	}
	~sub_process() noexcept
	{
	}

	sub_process& operator=(const sub_process&) = delete;
	sub_process& operator=(sub_process&& src) noexcept
	{
		m_process = rv_forward(src.m_process);
		m_iExitCode = src.m_iExitCode;
		return *this;
	}

	bool Create(const char_s* szCmd) noexcept
	{
		return m_process.Create(szCmd);
	}
	bool CheckRunning() noexcept
	{
		return m_process.GetState(m_iExitCode) > 0;
	}
	void Terminate() noexcept
	{
		bool bRet = m_process.Kill();
		(void)bRet;
	}
	void WaitForEnd() noexcept
	{
		m_process.WaitForEnd(m_iExitCode);
	}
	int32_t GetExitCode() const noexcept
	{
		return m_iExitCode;
	}
	void Reset() noexcept
	{
		m_process.ResetPid();
	}

protected:
	_x_child_process m_process;
	int32_t m_iExitCode;
};

//rio_process

class rio_process
{
public:
	rio_process() noexcept : m_iExitCode(-1)
	{
	}
	rio_process(const rio_process&) = delete;
	rio_process(rio_process&& src) noexcept : m_process(rv_forward(src.m_process)),
						m_iExitCode(src.m_iExitCode)
	{
	}
	~rio_process() noexcept
	{
	}

	rio_process& operator=(const rio_process&) = delete;
	rio_process& operator=(rio_process&& src) noexcept
	{
		m_process = rv_forward(src.m_process);
		m_iExitCode = src.m_iExitCode;
		return *this;
	}

	bool Create(const char_s* szCmd) noexcept
	{
		return m_process.Create(szCmd);
	}
	bool ReadFromPipe(void* pData, uint32_t uSize, uint32_t& uRead) noexcept
	{
		ssize_t ret = m_process.ReadFromPipe(pData, uSize);
		uRead = (uint32_t)ret;
		return ret != -1;
	}
	bool WriteToPipe(const void* pData, uint32_t uSize, uint32_t& uWritten) noexcept
	{
		ssize_t ret = m_process.WriteToPipe(pData, uSize);
		uWritten = (uint32_t)ret;
		return ret != -1;
	}
	void Terminate() noexcept
	{
		bool bRet = m_process.Kill();
		(void)bRet;
	}
	void WaitForEnd() noexcept
	{
		m_process.WaitForEnd(m_iExitCode);
	}
	int32_t GetExitCode() const noexcept
	{
		return m_iExitCode;
	}
	void Reset() noexcept
	{
		m_process.ClosePipeStdout();
		m_process.ClosePipeStdin();
		m_process.ResetPid();
	}

protected:
	_x_rio_process m_process;
	int32_t m_iExitCode;
};

////////////////////////////////////////////////////////////////////////////////
